package com.mmall.concurrency;

import com.mmall.concurrency.annoations.NotThreadSafe;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

@Slf4j
@NotThreadSafe
public class ConcurrencyTest {

    // 请求总数
    public static int clientTotal = 5000;
    // 同时并发执行的线程数
    public static int threadTotal = 200;
    // count 用来计数
    public static int count = 0;

    /**
     * 模拟并发执行
     */
    public static void main(String[] args) throws Exception {
        // 创建线程池
        ExecutorService executorService = Executors.newCachedThreadPool();
        // 定义信号量, Semaphore,传入并发的线程数
        final Semaphore semaphore = new Semaphore(threadTotal);
        // 计数门栓.希望所有请求结束后计数结果,所以这里传入 请求总数.
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        // 循环 clientTotal 次请求
        for (int i = 0; i < clientTotal; i++) {
            // 请求放入线程池,JDK1.8 Lambda表达式
            executorService.execute(() -> {
                try {
                    semaphore.acquire();  // 信号量捕获,不能捕获就阻塞
                    add();
                    semaphore.release();  // 信号量释放
                } catch (Exception e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown(); // 门栓减一
            });
        }
        countDownLatch.await();  // 主线程停止等待
        executorService.shutdown();  // 关闭线程池
        log.info("count:{}", count);
    }

    /**
     * 计数方法 自增1
     */
    private static void add() {
        count++;
    }
}
